import { NextFunction, Request, Response } from "express";

import registerSer from "./service";
import userService from "../../common/services/user";
import { RegisterOpt } from "./types";
import { checkField, encrypt } from "../../utils/common";
import Base from "../../common/controller/base";

class RegisterContrller extends Base {
  register = async (req: Request, res: Response, next: NextFunction) => {
    const info = req.body as RegisterOpt;
    // 1. 获取用户名和密码
    let { username, password, role } = info;

    // 校验参数role
    if (!checkField(role)) return next({ code: 400, msg: "角色不能为空" });

    if (!/^stu|tch$/.test(role))
      return next({ code: 400, msg: "角色只能为tch(老师)或者stu(学生)" });


    try {
      // 2. 判断是否重复注册
      const isExist = await userService.isUserExist(username);

      // 已经存在了该用户
      if (isExist) {
        return next({ msg: "该用户已经被注册过了", code: 200 });
      }

      // 3. 对密码进行加密
      info.password = encrypt(password);

      // 4. 注册
      await registerSer.register(info);
      this.success(res, { msg: "注册成功", data: "" });
    } catch (e) {
      next({ msg: "服务器出错", code: 500 });
    }
  };
}

export default new RegisterContrller();
